package com.hongfasoft;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.hongfasoft.util.HttpRequestUtil;

public class GetUserInfoServlet extends HttpServlet
{
	static Logger logger = Logger.getLogger(GetUserInfoServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		// String getCodeRequest =
		// "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4fbfd12de50a98c7&redirect_uri=http://121.40.177.191/GetUserInfoServlet&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
		String code = req.getParameter("code");
		String btntype = req.getParameter("btntype");
		// https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
		String param = "appid=wx4fbfd12de50a98c7&secret=a141a193025a3b4f91b10572d7946651&code=" + code + "&grant_type=authorization_code";
		// System.out.println("btntype==="+btntype+",code11111="+code);
		String response = HttpRequestUtil.sendGet("https://api.weixin.qq.com/sns/oauth2/access_token", param);

		Gson gson1 = new Gson();
		OAuthInfo oAuthInfo = gson1.fromJson(response, OAuthInfo.class);
		// System.out.println("response=="+response);

		try
		{
			System.out.println("================ url ============ \r\nhttp://115.29.233.142:9080/hello?user=" + oAuthInfo.getOpenid() + "&rmd=" + System.currentTimeMillis());
			resp.sendRedirect("http://115.29.233.142:9080/hello?user=" + oAuthInfo.getOpenid() + "&rmd=" + System.currentTimeMillis());
		} catch (Exception e)
		{
			e.printStackTrace();
		}

	}

}
